import getopt
import sys
from datetime import datetime, timedelta

import pandas as pd

from air_web.data_platform import sql_engine
from air_web.web_flask.tools.air_condition_show import get_baseline_day


def query_data(data_time, p_field):
    sql = f"""select type_id, p_kt_sum as {p_field}
              from orgno_typeid_15min
              where data_time = '{data_time}'
                and org_no = 51101
                and type_id in (101,102)
              order by type_id
           """
    df = sql_engine.query(sql)
    return df


def main(data_time, baseline_time):

    if baseline_time is None:
        baseline_time = get_baseline_day(data_time[:10])
        baseline_time = baseline_time + data_time[10:]
        print(f"基线日:{baseline_time}")

    yesterday = datetime.strptime(data_time, '%Y-%m-%d %H:%M:%S') - timedelta(days=1)

    today_df = query_data(data_time, 'p_today')
    yesterday_df = query_data(yesterday, 'p_yesterday')
    baseline_df = query_data(baseline_time, 'p_baseline')

    res_df = pd.merge(today_df, yesterday_df, on='type_id', how='outer')
    res_df = pd.merge(res_df, baseline_df, on='type_id', how='outer')

    res_df['p_yesterday_diff'] = res_df['p_today'] - res_df['p_yesterday']
    res_df['p_baseline_diff'] = res_df['p_today'] - res_df['p_baseline']

    print(res_df)


if __name__ == "__main__":

    data_time = "2022-12-15 08:00:00"
    baseline_time = None

    opts, args = getopt.getopt(sys.argv[1:], "t:b:")
    for opt, val in opts:
        if opt == "-t":
            data_time = val
        if opt == '-b':
            baseline_time = val

    main(data_time, baseline_time)
